package com.uha.reggie.filter;

/**
 * @author uha
 * @date 2023/6/15
 * @apiNote
 */

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.uha.reggie.common.ReggieResult;
import com.uha.reggie.util.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

/**
 * 检查用户是否登录
 * 注意 启动类需要加上扫描注解 @ServletComponentScan
 */
@WebFilter(filterName = "LoginCheck",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器 支持通配符
    public static  final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求的URI
        String requestURI = request.getRequestURI();

        //log.info("拦截到请求：{}", request.getRequestURI());

        String[] urls = new String[]{
            "/employee/login",
                "/employee/logout",
                "/backend/**","/front/**",
                "/backend/page/demo/upload.html",
                "/user/sendMsg",
                "/user/login"

        };
        //2.判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        //3.如果不需要处理 直接放行

        if (check){
            filterChain.doFilter(request,response);
            return;
        }
        //4.判断登录状态

       if(request.getSession().getAttribute("employee") != null){

           Long empId = (Long) request.getSession().getAttribute("employee");
           //将获取到的用户id放入
           BaseContext.setCurrentId(empId);
           log.info("=========================================");
           log.info("将获取到的用户empId放入: " + empId);
           log.info("=========================================");
           //放行

           filterChain.doFilter(request,response);
            return;
       }

        if(request.getSession().getAttribute("user") != null){

            Long userId = (Long) request.getSession().getAttribute("user");
            //将获取到的用户id放入
            BaseContext.setCurrentId(userId);
            log.info("=========================================");
            log.info("将获取到的用户userId放入: " + userId);
            log.info("=========================================");
            //放行

            filterChain.doFilter(request,response);
            return;
        }

        //5 如果未登录则返回未登录结果  通过输出流的方式向客户端页面响应数据
        //【因为前端有拦截器处理 {request.js  : 47}】
        response.getWriter().write(JSON.toJSONString(ReggieResult.error("NOTLOGIN")));
        return;



    }

    /**
     * 路径匹配 检查本次请求是否需要放行
     * @param urls urls
     * @param requestURI requestURI
     * @return Boolean
     */
    public boolean check(String[] urls,String requestURI){

        for(String url :urls){
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;

    }

}
